<template>
    <div class="chat-container">
      <van-nav-bar title="云端小助手" left-text="返回" @click-left="$router.go(-1)" />
      <div class="message-container">
        <div v-for="msg in messages" :key="msg.id" class="message" :class="{ 'is-user': msg.isUser }">
          <div v-html="msg.text"></div>
        </div>
      </div>
      <div class="input-area">
        <van-field v-model="userInput" v-if="!isTalking" placeholder="请输入消息..." @keyup.enter="sendMessage" />
        <van-button v-if="!isTalking" type="primary" @click="sendMessage">发送</van-button>
        <van-button v-else type="danger" @click="stopTalking">停止对话</van-button>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, reactive } from 'vue';
  import axios from 'axios';
  
  export default {
    setup() {
      const messages = reactive([]);
      const userInput = ref('');
      const isTalking = ref(false);
  
      const addMessage = (text, isUser = false) => {
        messages.push({ id: Date.now(), text, isUser });
      };
  
      const typeMessage = (message) => {
        let index = 0;
        let currentMessage = "";  // 存储逐字累积的消息内容
        addMessage("", false);  // 初始创建一个空消息
        const lastMessageIndex = messages.length - 1;  // 获取最后一个消息的索引
  
        const timer = setInterval(() => {
          if (index < message.length) {
            currentMessage += message.charAt(index);
            messages[lastMessageIndex].text = currentMessage;  // 更新已存在的消息内容
            index++;
          } else {
            clearInterval(timer);
            isTalking.value = false;
          }
        }, 100);
      };
  
      const sendMessage = async () => {
        const apiUrl = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8081/api'; 
        console.log('apiUrl---',apiUrl,process.env)
        if (userInput.value.trim()) {
          addMessage(userInput.value, true);
          isTalking.value = true;
          try {
            const response = await axios.post(`${apiUrl}/chat`, {
              messages: [{ role: "user", content: userInput.value }]
            });
            if (response.status === 200 && response.data && response.data.choices.length > 0) {
              const assistantMessage = response.data.choices[0].message.content;
              typeMessage(assistantMessage);
            } else {
              addMessage('未收到有效的回复或回复为空', false);
            }
          } catch (error) {
            console.error('与聊天 API 通信出错:', error);
            addMessage('无法连接到服务器。', false);
          }
          userInput.value = '';
          isTalking.value = false;
        }
      };
  
      const stopTalking = () => {
        isTalking.value = false;
        addMessage('对话已停止。', false);
      };
  
      return { messages, userInput, isTalking, sendMessage, stopTalking };
    }
  };
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }
  .message-container {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f8f8f8;
  }
  .message {
    margin-bottom: 10px;
    padding: 10px;
    background-color: white;
    border-radius: 10px;
  }
  .message.is-user {
    background-color: #b3d4fc;
    align-self: flex-end;
  }
  .input-area {
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid #ddd;
  }
  </style>
  